<template>
  <div class="subject_information_wrapper">
    <div class="details-layout">
      <!-- 按钮部分 -->
      <el-row class="top-operate-row">
        <el-button size="mini" type="primary" @click="handleRefresh()">刷新</el-button>
        <el-button size="mini" icon="el-icon-plus" type="primary" v-if="permissionController('subject::info::add')" @click="handleAdd">新增受试者</el-button>
        <column-control
          v-model="tableColumns"
          size="mini"
          style="margin-left: 8px; margin-right: 8px; float: right"
        ></column-control>
      </el-row>
      <!-- 表格部分 -->
      <el-table
        :data="eCRFDesignList"
        stripe
        style="width: 100%"
        size="mini"
        row-key="id"
        :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
        @cell-click="tableTransfo"
      >
        <el-table-column type="index" align="center" label="序号" width="50"> </el-table-column>
        <template v-for="(column, index) in tableColumns">
          <el-table-column
            v-if="column.visible"
            :key="index"
            :label="column.name"
            :show-overflow-tooltip="true"
            align="center"
            :width="column.width"
          >
            <template slot-scope="scope">
              <!-- 编辑按钮 -->
              <div v-if="specialColumn.includes(column.key)">
                <span v-if="column.key === 'SUBJID'" class="table-column-text active-color">{{
                  scope.row[column.key]
                }}</span>
                <span v-else class="table-column-text">{{ scope.row[column.key] }}</span>
                <span v-if="permissionController('subject::info::edit')">
                  <el-button
                    @click.stop="handleEdit(scope.row, column.key)"
                    style="cursor: pointer"
                    size="mini"
                    icon="el-icon-edit"
                    circle
                  ></el-button>
                </span>
              </div>
              <div v-else-if="column.key === 'STUDYID'">
                <span>{{ projectCode || ''}}</span>
              </div>
              <span v-else>{{ scope.row[column.key] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <el-row type="flex" justify="end">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageParams.pageNo"
          :page-size="pageParams.pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 24px"
        >
        </el-pagination>
      </el-row>
      <!-- 新增弹窗 -->
      <AddSubject
        :addVisible.sync="addVisible"
        :projectCode="projectCode"
        :formItemList="originTableHeadData"
        :coreNameOptions="coreNameOptions"
        :subjectStateOptions="subjectStateOptions"
        :originTableHeadData="originTableHeadData"
        @handleAddCancel="handleAddCancel"
      ></AddSubject>
      <!-- 编辑弹窗 -->
      <el-dialog title="编辑" :visible="editVis" width="500px" @close="handleCancel()">
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
          <el-form-item label="受试者姓名缩写：" prop="SUBJINIT" v-if="displayOfItems.SUBJINIT">
            <el-input size="mini" style="width: 80%" v-model="formData.SUBJINIT"></el-input>
          </el-form-item>
          <el-form-item label="研究者：" prop="INVNAM" v-if="displayOfItems.INVNAM">
            <el-input size="mini" style="width: 80%" v-model="formData.INVNAM"> </el-input>
          </el-form-item>
          <el-form-item label="受试者代码：" prop="SUBJID" v-if="displayOfItems.SUBJID">
            <el-input size="mini" style="width: 80%" v-model="formData.SUBJID"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" size="mini" @click="handleConfirm()">确认</el-button>
          <el-button size="mini" @click="handleCancel()">取消</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations } from 'vuex'
import AddSubject from './component/add-subject.vue'
import { defaultColumn } from './data'
import { permissionController } from '@/utils/index'

export default {
  components: {
    AddSubject,
  },
  data() {
    return {
      formData: {
        SUBJINIT: '',
        INVNAM: '',
        SUBJID: '',
      },
      innerDiaTitle: '编辑缩写',
      innerDiaVis: false,
      eCRFDesignList: [],
      tableColumns: [],
      addVisible: false,
      editVis: false,
      displayOfItems: {
        SUBJINIT: true,
        INVNAM: true,
        SUBJID: true,
      },
      defaultColumn,
      formRules: {
        SUBJINIT: [
          {
            required: true,
            message: '请填写',
            trigger: 'blur',
          },
        ],
        SUBJID: [
          {
            required: true,
            message: '请填写',
            trigger: 'blur',
          },
        ],
        reason: [
          {
            required: true,
            message: '请填写',
            trigger: 'blur',
          },
        ],
      },
      specialColumn: ['SUBJINIT', 'INVNAM', 'SUBJID'],
      total: null,
      pageParams: {
        pageNo: 1,
        pageSize: 10,
      },
      coreIds: [],
      projectDatabaseId: '',
      coreNameOptions: [],
      subjectStateOptions: [],
      // 原始的表头数据
      originTableHeadData: [],
      editKey: '',
      // 原始表格数据
      originTableData: [],
      projectId: '',
      environment: '',
      subjectStateOptionsEnums: {},
      projectCode: '',
      editRow: {}
    }
  },
  created() {
    this.databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}
    this.projectDatabaseId = localStorage.getItem('project-database-Id') || ''
    this.projectId = localStorage.getItem('sys-project-id') || ''
    this.environment = localStorage.getItem('environment') || '0'
    this.coreIds = JSON.parse(localStorage.getItem('coreIds'))
    this.projectCode = localStorage.getItem('sys-project-code')

    this.getTableColumnsData()
    this.getTableData()
  },
  mounted() {},

  methods: {
    permissionController,
    ...mapActions('subjectInformation', [
      'getSubjectInfoListTable',
      'getPageSubjectInfo',
      'addSaveSubject',
      'editSaveSubject',
      'getUpdateSubjectInfo',
    ]),
    ...mapActions('subjectInformation', ['getUpdateSubjectInfo']),
    ...mapActions('subjectStatus', ['qryProjectSubjectStatusList']),
    ...mapMutations({
      clear: 'treatment/clear'
    }),

    // 刷新
    handleRefresh() {
      this.getTableData()
    },

    //  获取表格数据
    async getTableData() {
      const data = {
        coreIds: this.coreIds,
        pageNo: this.pageParams.pageNo + '',
        pageSize: this.pageParams.pageSize + '',
        projectId: this.projectId,
        environment: this.environment,
      }
      const res = await this.getPageSubjectInfo({ data })
      console.log(res, 'res')
      this.originTableData = res.data.records
      const arr = []
      res.data.records.forEach(item => {
        const obj = {}
        item.subjectDetails.forEach(it => {
          obj[it.variable] = it.variable === 'STATUS' ? it.variableValueName : it.variableValue
          obj.id = item.id
          obj.coreId = item.coreId
        })
        arr.push(obj)
      })
      this.eCRFDesignList = arr
      this.total = res.data.total
    },

    // 获取动态表头数据
    async getTableColumnsData() {
      const params = {
        projectDatabaseId: this.projectDatabaseId,
        projectId: this.projectId,
        environment: this.environment,
        crfName: 'SUBJECT',
      }
      const res = await this.getSubjectInfoListTable({ params })
      this.originTableHeadData = res.data || []
      if (this.originTableHeadData.length === 0) {
        // 空表头展示默认字段
        this.tableColumns = this.defaultColumn
      } else {
        this.tableColumns = this.originTableHeadData.map(item => {
          const obj = {
            name: item.variableName,
            key: item.variable,
            visible: true,
          }
          if (this.specialColumn.includes(item.variable)) {
            obj.width = 150
          }
          return obj
        })
      }
    },
    // 页码变化
    handleCurrentChange(val) {
      this.pageParams.pageNo = val
      this.getTableData()
    },
    handleSizeChange(val) {
      this.pageParams.pageSize = val
      this.getTableData()
    },

    // 获取受试者状态
    async getSubjectStateOptionsData() {
      const params = {
        projectId: this.projectId,
      }
      const res = await this.qryProjectSubjectStatusList({ params })
      if (this.coreNameOptions.length > 0) {
        this.addVisible = true
      } else {
        this.$message.error('项目暂未创建中心，请联系系统数据库管理员~')
        return false
      }
      this.subjectStateOptions = res.data || []
      this.subjectStateOptions.forEach(item => {
        this.subjectStateOptionsEnums[item.codeValue] = item.statusName
      })
    },

    // 点击新增
    handleAdd() {
      // 受试者状态
      this.getSubjectStateOptionsData()
      // 中心下拉选项
      // this.getCoreNameOptionsData()
      this.coreNameOptions = JSON.parse(localStorage.getItem('coreOfficialOptions'))
    },

    // 新增受试者取消
    handleAddCancel(type) {
      this.addVisible = false
      if (type === 'refresh') {
        this.getTableData()
      }
    },

    // 点击编辑
    handleEdit(row, key) {
      this.editRow = row
      this.editVis = true
      if (key === 'SUBJINIT') {
        this.innerDiaTitle = '编辑缩写'
        this.displayOfItems.SUBJINIT = true
        this.displayOfItems.INVNAM = false
        this.displayOfItems.SUBJID = false
      } else if (key === 'INVNAM') {
        this.innerDiaTitle = '编辑研究者'
        this.displayOfItems.SUBJINIT = false
        this.displayOfItems.INVNAM = true
        this.displayOfItems.SUBJID = false
      } else if (key === 'SUBJID') {
        this.innerDiaTitle = '编辑受试者'
        this.displayOfItems.SUBJINIT = false
        this.displayOfItems.INVNAM = false
        this.displayOfItems.SUBJID = true
      }
      this.formData[key] = row[key]
      this.editKey = key
      const obj = this.originTableData.find(item => item.id === row.id)
      const objObj = obj.subjectDetails.find(item => item.variable === key)
      this.formData.id = objObj.id
    },

    publicClose() {
      this.$refs.formRef.resetFields()
      this.editVis = false
    },
    async handleConfirm() {
      await this.$refs.formRef.validate()
      const data = {
        id: this.formData.id,
        variableValue: this.formData[this.editKey],
        projectId: this.projectId,
        coreId: this.editRow.coreId
      }
      const res = await this.editSaveSubject({ data })
      if (res.code === 200) {
        this.getTableData()
        this.$message.success('修改成功！')
        this.publicClose()
      }
    },
    handleCancel() {
      this.publicClose()
    },
    tableTransfo (row) {
      this.clear()
      this.$router.push({
        path: '/ecrf-detail',
        query: {
          id: row.id,
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.subject_information_wrapper {
  background-color: $white;
  height: 100%;

  .details-layout {
    padding: 12px;
    background-color: $white;
  }
  .top-operate-row {
    margin-bottom: 20px;
  }
  .table-column-text {
    display: inline-block;
    width: 70px;
    cursor: pointer;
  }
  .active-color {
    color: rgb(117, 60, 202);
  }
}
</style>
